package com.cxh.util;

import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import com.shimne.util.StringUtil;

/**
 * 字符串处理帮助类
 * @author cnc
 *
 */
public class StringUtils {
	/**
     * 将汉字转换为全拼
     * @param src 将汉字转换成汉语拼音并获得全称
     * @return
     */
    public static String getPingYin(String src) {  
  
        char[] t1 = null;  
        t1 = src.toCharArray();  
        String[] t2 = new String[t1.length];  
        HanyuPinyinOutputFormat t3 = new HanyuPinyinOutputFormat();  
          
        t3.setCaseType(HanyuPinyinCaseType.LOWERCASE);  
        t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE);  
        t3.setVCharType(HanyuPinyinVCharType.WITH_V);  
        String t4 = "";  
        int t0 = t1.length;  
        try {  
            for (int i = 0; i < t0; i++) {  
                // 判断是否为汉字字符  
                if (java.lang.Character.toString(t1[i]).matches(  
                        "[\\u4E00-\\u9FA5]+")) {  
                    t2 = PinyinHelper.toHanyuPinyinStringArray(t1[i], t3);  
                    t4 += t2[0];  
                } else  
                    t4 += java.lang.Character.toString(t1[i]);  
            }  
            // System.out.println(t4);  
            return t4;  
        } catch (BadHanyuPinyinOutputFormatCombination e1) {  
            e1.printStackTrace();  
        }  
        return t4;  
    }  
    
    /**
     * 过滤特殊字符
     * @param str
     * @return
     * @throws PatternSyntaxException
     */
    public static String StringFilter(String str) throws PatternSyntaxException { 
    	// 只允许字母和数字 // String regEx ="[^a-zA-Z0-9]"; 
    	// 清除掉所有特殊字符 
    	String regEx="[\\s~·`!！@#￥$%^……&*（()）\\-——\\-_=+【\\[\\]】｛{}｝\\|、\\\\；;：:‘'“”\"，,《<。.》>、/？?]";
    	Pattern p = Pattern.compile(regEx); 
    	Matcher m = p.matcher(str);
    	return m.replaceAll("").trim();
    } 
    
    /**
     *将集合转换成字符串
     * @param sql
     * @return
     */
    public static String listToString(List<String> list){
    	 String keywodString="";
    	 for(String key:list){
			 keywodString+=key+",";
		 }
		return keywodString;
    	
    }
    
    /**
     * 获得字符串中的中文部分
     * @param paramValue
     * @return
     */
    public static String nsgString(String paramValue){
    	String regex = "([\u4e00-\u9fa5]+)";
	 	String str = "";
	 	Matcher matcher = Pattern.compile(regex).matcher(paramValue);
	 	while (matcher.find()) {
	 		str+= matcher.group(0);
	 	}
		return str;
    }
    
    /**
     * 将阿拉伯数字转换成中文数字
     * @param number 阿拉伯数字
     * @return
     */
    public static String toChinese(String number) {
        String[] s1 = { "零", "一", "二", "三", "四", "五", "六", "七", "八", "九" };
        String[] s2 = { "十", "百", "千", "万", "十", "百", "千", "亿", "十", "百", "千" };

        String result = "";

        int n = number.length();
        for (int i = 0; i < n; i++) {

            int num = number.charAt(i) - '0';

            if (i != n - 1 && num != 0) {
            	if(n>2|n==2&num!=1){
            		 result += s1[num] + s2[n - 2 - i];
            	}
            	else{
            		result +=s2[n - 2 - i];
            	}
               
            }  else {
                result += s1[num];
            }
        }
        //如果结尾有零 
        if(result.length()>1){
        	if(result.lastIndexOf("零") == result.length()-1){  
            	result = result.substring(0, result.length()-1);  
            }
        }else{
        	
        	return result;
        }
        
        return result;
    }
    /**
     * 获得正则表达式匹配到的字符串
     * @param str 正则表达式
     * @param question 字符串
     * @return 匹配到的字符串
     */
    public static String getStringValue(String str,String question){
		String resault="";
		Pattern pattern = Pattern.compile(str);
		 Matcher matcher = pattern.matcher(question);
		 if(matcher.find()){  
//		   for(int i=0; i<=matcher.groupCount(); i++){
//			    resault+=matcher.group(i);
//			}
			 resault+=matcher.group(1);
		 }
		return resault;
    }
    
    /**
     * 获得正则表达式匹配到的字符串
     * @param str 正则表达式
     * @param question 字符串
     * @return 匹配到的字符串
     */
    public static String getStringValueCopy(String str,String question){
		String resault="";
		Pattern pattern = Pattern.compile(str);
		Matcher matcher = pattern.matcher(question);
		if(matcher.find()){  
			 resault+=matcher.group(0);
		}
		return resault;
    }
    
	/**
	 * 获得正则表达式匹配到的一个字符串
	 * @param str 正则表达式
	 * @param question 字符串
	 * @return 匹配到的字符串
	 */
	public static String getCheckValue(String str,String question){
		String resault="";
		Pattern pattern = Pattern.compile(str);
		Matcher matcher = pattern.matcher(question);
		if(matcher.find()){
			resault=matcher.group(1);
		}
		return resault;
	}
   
    /**
     * 获得字符串中所有的数字字符串
     * @param stringVale
     * @return
     */
    public static List<String> getNumberStirng(String stringVale){
    	List<String> list=null;
    	if(StringUtil.notTrimEmpty(stringVale)){
    		String regEx = "[0-9]+";
    		Pattern pat = Pattern.compile(regEx);
    		Matcher mat = pat.matcher(stringVale);
    			list=new ArrayList<String>();
    		while(mat.find()){
        		list.add(mat.group());
        	}
    	}
		return list;   	
    }
    
    /**
     * 使用正则表达式删除匹配到的数据
     * @param str 正则表达式
     * @param question 待处理字符串
     * @return
     */
    public static String deleteStringValue(String str,String question){
    	String result=question;
    	Pattern pattern = Pattern.compile(str);
		Matcher matcher = pattern.matcher(question);
		if(matcher.find()){
			 result=matcher.replaceAll("");
		}
		return result;
    }
    
    /**
     * 根据正则表达式判断
     * @param str 规则正则表达式
     * @param stringValue 待判断字符串
     * @return
     */
    public static boolean checkRegular(String str,String stringValue){
    	
    	if(StringUtil.isTrimEmpty(str) || StringUtil.isTrimEmpty(stringValue)){
    		return false;
    	}
    	Pattern pattern = Pattern.compile(str);
		Matcher matcher = pattern.matcher(stringValue);
		return matcher.find();
    	
    }

    /**
     * @描述: 截取特定开头特定结尾的字符串并去掉头和尾
     * @参数： @param sta
     * @参数： @param end
     * @参数： @param data
     * @throws
     */
    public static String subStringSpecial(String sta, String end, String data) {
		Matcher m1 = Pattern.compile(sta + ".*?" + end,
				Pattern.CASE_INSENSITIVE).matcher(data);
		String nString = null;
		while (m1.find()) {
			nString = m1.group();	
			if (nString != null && nString.length() > 0) {
				if(StringUtil.notTrimEmpty(sta)){
					Matcher m_ = Pattern.compile(sta,
							Pattern.CASE_INSENSITIVE).matcher(nString);
					if (m_.find()) {//掐头
						nString = m_.replaceAll("");
					}
				}
				if(StringUtil.notTrimEmpty(end) && !end.equals("$")){
					Matcher m__ = Pattern.compile(end,
							Pattern.CASE_INSENSITIVE).matcher(nString);
					if (m__.find()) {//去尾
						nString = m__.replaceAll("");
					}
				}
			}	
		}
		return nString;
	}
    
    /**
     * @描述: 截取特定开头特定结尾的字符串
     * @参数： @param sta
     * @参数： @param end
     * @参数： @param data
     * @throws
     */
    public static String subStringSpecialNotDel(String sta, String end, String data) {
		Matcher m1 = Pattern.compile(sta + ".*?" + end,
				Pattern.CASE_INSENSITIVE).matcher(data);
		String nString = null;
		while(m1.find()) {
			nString = m1.group();	
		}
		return nString;
	}
    
    
    /**
     * @描述: 截取特定开头特定结尾的字符串组
     * @参数： @param sta
     * @参数： @param end
     * @参数： @param data
     * @throws
     */
    public static List<String> subStringsSpecial(String sta, String end, String data) {
    	List<String> returnList = new ArrayList<String>();
		Matcher m1 = Pattern.compile(sta + ".*?" + end,
				Pattern.CASE_INSENSITIVE).matcher(data);
		String nString = null;
		while (m1.find()) {
			nString = m1.group();	
			if (nString != null && nString.length() > 0) {
				returnList.add(nString);
			}	
		}
		return returnList;
	}
    
    /**
     * 获得字符串中符合条件的数据个数
     * @param str 正则表达式
     * @param data 字符串数据
     * @return
     */
    public static Integer getSize(String str,String data){
		 Pattern pattern = Pattern.compile(str);
		 Matcher matcher= pattern.matcher(data);
		 List<String> list=new ArrayList<String>();
		 int number=0;
		 while(matcher.find()){  
		
			   for(int i=0; i<=matcher.groupCount(); i++){  
				    list.add(matcher.group(0));
				}  
			   number++;
		 }
		return number;
    }
    
    /**
     * 获得字符串中所有被匹配到的数据
     * @param str  正则表达式
     * @param data 匹配的字符串数据
     * @return
     */
    public static List<String> getArray(String str,String data){
    	List<String> list=new ArrayList<String>();
    	 Pattern pattern = Pattern.compile(str);
		 Matcher matcher= pattern.matcher(data);
		 int number=0;
		 while(matcher.find()){  
			   for(int i=0; i<=matcher.groupCount(); i++){  
				    list.add(matcher.group(0));
				}  
		 }
		return list;
    }
    
    /**
     * 将中文数字转换成阿拉伯数字
     * @param chineseNumber  中文数字
     * @return
     */
    public static int getNum(String chineseNumber){
        int result = 0;
        int temp = 1;//存放一个单位的数字如：十万
        int count = 0;//判断是否有chArr
        char[] cnArr = new char[]{'一','二','三','四','五','六','七','八','九'};
        char[] chArr = new char[]{'十','百','千','万','亿'};
        for (int i = 0; i < chineseNumber.length(); i++) {
            boolean b = true;//判断是否是chArr
            char c = chineseNumber.charAt(i);
            for (int j = 0; j < cnArr.length; j++) {//非单位，即数字
                if (c == cnArr[j]) {
                    if(0 != count){//添加下一个单位之前，先把上一个单位值添加到结果中
                        result += temp;
                        temp = 1;
                        count = 0;
                    }
                    // 下标+1，就是对应的值
                    temp = j + 1;
                    b = false;
                    break;
                }
            }
            if(b){//单位{'十','百','千','万','亿'}
                for (int j = 0; j < chArr.length; j++) {
                    if (c == chArr[j]) {
                        switch (j) {
                        case 0:
                            temp *= 10;
                            break;
                        case 1:
                            temp *= 100;
                            break;
                        case 2:
                            temp *= 1000;
                            break;
                        case 3:
                            temp *= 10000;
                            break;
                        case 4:
                            temp *= 100000000;
                            break;
                        default:
                            break;
                        }
                        count++;
                    }
                }
            }
            if (i == chineseNumber.length() - 1) {//遍历到最后一个字符
                result += temp;
            }
        }
        return result;
    }
    /**
     * 将数组转换成集合
     * @param strings
     * @return
     */
    public static List<String> loadList(String[] strings){
		if(strings==null || strings.length<=0){
			return null;
		}
		List<String> list=new ArrayList();
		for(String obj:strings){
			list.add(obj);
		}
		return list;
	}
    /**
     * 字符串转ASCII
     * @param value
     * @return
     */
    public static String stringToAscii(String value)  
    {  
        StringBuffer sbu = new StringBuffer();  
        char[] chars = value.toCharArray();   
        for (int i = 0; i < chars.length; i++) {  
            if(i != chars.length - 1)  
            {  
                sbu.append((int)chars[i]).append(",");  
            }  
            else {  
                sbu.append((int)chars[i]);  
            }  
        }  
        return sbu.toString();  
    }
    /**
     * 判断字符串去空格之后是否为空
     * @param value
     * @return
     */
    public static boolean isNull(String value){
    	boolean bean=true;
    	if(StringUtil.isNull(value)){
    		return bean;
    	}
    	value=value.replaceAll(" ","");
    	if(StringUtil.isNull(value) || StringUtil.isTrimEmpty(value)){
    		return bean;
    	}
		return false;
    	
    }
    /**
      * @描述：中文转Unicode   
      * @作者：YangHL 
      * @创建时间：2018年5月24日 下午2:38:27   
      * @修改人：  
      * @修改时间：  
      * @修改备注：   
      * @param @param gbString
      * @param @return
      * @return String
      * @throws
      * @version
     */
    public static String StringToUnicode(String gbString) {   //gbString = "测试"  
        char[] utfBytes = gbString.toCharArray();   //utfBytes = [测, 试]  
        String unicodeBytes = "";     
        for (int byteIndex = 0; byteIndex < utfBytes.length; byteIndex++) {     
            String hexB = Integer.toHexString(utfBytes[byteIndex]);   //转换为16进制整型字符串  
              if (hexB.length() <= 2) {     
                  hexB = "00" + hexB;     
             }     
             unicodeBytes = unicodeBytes + "\\u" + hexB;     
        }     
        return unicodeBytes;     
    } 
    
    /**
     * @描述：中文转Unicode   
     * @作者：YangHL 
     * @创建时间：2018年5月24日 下午2:38:27   
     * @修改人：  
     * @修改时间：  
     * @修改备注：   
     * @param @param gbString
     * @param @return
     * @return String
     * @throws
     * @version
    */
   public static String StringToUnicode2(String gbString) {   //gbString = "测试"  
       char[] utfBytes = gbString.toCharArray();   //utfBytes = [测, 试]  
       String unicodeBytes = "";     
       for (int byteIndex = 0; byteIndex < utfBytes.length; byteIndex++) {     
           String hexB = Integer.toHexString(utfBytes[byteIndex]);   //转换为16进制整型字符串  
             if (hexB.length() <= 2) {     
                 hexB = "00" + hexB;     
            }     
            unicodeBytes = unicodeBytes + "%u" + hexB;     
       }     
       return unicodeBytes;     
   } 
   /**
    * 
     * @描述：   不带单位的纯中文数字换成阿拉伯数字
     * @作者：JingSY
     * @创建时间：2018-6-12 上午10:10:36   
     * @修改人：  
     * @修改时间：  
     * @修改备注：   
     * @param @param chineseNumber
     * @param @return
     * @return String
     * @throws
     * @version
    */
   public static String getNumber(String chineseNumber){
	   
	   chineseNumber=chineseNumber.replaceAll("零", "0");
	   chineseNumber=chineseNumber.replaceAll("幺", "1");
	   chineseNumber=chineseNumber.replaceAll("一", "1");
	   chineseNumber=chineseNumber.replaceAll("二", "2");
	   chineseNumber=chineseNumber.replaceAll("三", "3");
	   chineseNumber=chineseNumber.replaceAll("四", "4");
	   chineseNumber=chineseNumber.replaceAll("五", "5");
	   chineseNumber=chineseNumber.replaceAll("六", "6");
	   chineseNumber=chineseNumber.replaceAll("七", "7");
	   chineseNumber=chineseNumber.replaceAll("八", "8");
	   chineseNumber=chineseNumber.replaceAll("九", "9");
	   
	   return chineseNumber;     
   }

   /**
	* 解码 Unicode \\uXXXX
	*
	* @param str
	* @return
	*/
   private static final Pattern P = Pattern.compile("\\\\u([0-9a-fA-F]{4})");

	public static String decodeUnicode(String str) {
		Charset set = Charset.forName("UTF-16");
		Matcher m = P.matcher(str);
		int start = 0;
		int start2 = 0;
		StringBuffer sb = new StringBuffer();
		while (m.find(start)) {
			start2 = m.start();
			if (start2 > start) {
				String seg = str.substring(start, start2);
				sb.append(seg);
			}
			String code = m.group(1);
			int i = Integer.valueOf(code, 16);
			byte[] bb = new byte[4];
			bb[0] = (byte) ((i >> 8) & 0xFF);
			bb[1] = (byte) (i & 0xFF);
			ByteBuffer b = ByteBuffer.wrap(bb);
			sb.append(String.valueOf(set.decode(b)).trim());
			start = m.end();
		}
		start2 = str.length();
		if (start2 > start) {
			String seg = str.substring(start, start2);
			sb.append(seg);
		}
		return sb.toString();
	}

	/**
	 * 将下划线分隔的字符串转换驼峰命名格式
	 * @param underlineStr 下划线分隔的字符串
	 * @return java.lang.String
	 * @author zhaotao
	 * @date 2018/09/04 17:05
	 */
	public static String convertUnderlineStr2CamelCaseWith(String underlineStr) {
		String[] words = underlineStr.split("_");

		StringBuilder sb = new StringBuilder();
		sb.append(words[0]);

		for (int i = 1; i < words.length; i++) {
			sb.append(words[i].substring(0, 1).toUpperCase())
					.append(words[i].substring(1, words[i].length()));
		}

		return sb.toString();
	}

	/**
	 * 格式化消息
	 *
	 * @param pattern 消息模板。如：已为您将{2}{0}{1}
	 * @param param   {}中的参数，如灯光、打开、客厅
	 * @return java.lang.String
	 * @author zhaotao
	 * @date 2018/09/11 14:05
	 */
	public static String messageFormat(String pattern, Object... param) {
		MessageFormat messageFormat = new MessageFormat(pattern);
		return messageFormat.format(param);
	}

}
